# 更新KPI指标管理命令
from django.core.management.base import BaseCommand
from django.utils import timezone
import logging

from assets.analytics_engine import analytics_engine

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '更新KPI指标数据'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制更新所有指标，忽略更新频率限制'
        )
        
        parser.add_argument(
            '--metric-id',
            type=int,
            help='只更新指定ID的指标'
        )
        
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='试运行，不实际更新数据'
        )
    
    def handle(self, *args, **options):
        force = options['force']
        metric_id = options['metric_id']
        dry_run = options['dry_run']
        
        self.stdout.write(
            self.style.SUCCESS(f'开始更新KPI指标 - {timezone.now()}')
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('试运行模式 - 不会实际更新数据')
            )
        
        try:
            if metric_id:
                # 更新指定指标
                from assets.models_analytics import KPIMetric
                
                try:
                    kpi = KPIMetric.objects.get(id=metric_id, is_active=True)
                    
                    if dry_run:
                        self.stdout.write(f'将更新指标: {kpi.name}')
                        return
                    
                    # 计算新值
                    new_value = analytics_engine._calculate_kpi_value(kpi)
                    
                    # 更新指标
                    kpi.previous_value = kpi.current_value
                    kpi.current_value = new_value
                    kpi.last_updated = timezone.now()
                    
                    # 计算趋势
                    if kpi.previous_value and kpi.current_value:
                        if kpi.current_value > kpi.previous_value:
                            kpi.trend = 'up'
                        elif kpi.current_value < kpi.previous_value:
                            kpi.trend = 'down'
                        else:
                            kpi.trend = 'stable'
                    
                    kpi.save()
                    
                    self.stdout.write(
                        self.style.SUCCESS(
                            f'成功更新指标 "{kpi.name}": {kpi.previous_value} -> {kpi.current_value}'
                        )
                    )
                    
                except KPIMetric.DoesNotExist:
                    self.stdout.write(
                        self.style.ERROR(f'指标 ID {metric_id} 不存在或未启用')
                    )
                    
            else:
                # 更新所有指标
                if dry_run:
                    from assets.models_analytics import KPIMetric
                    metrics = KPIMetric.objects.filter(is_active=True, auto_update=True)
                    
                    self.stdout.write(f'将更新 {metrics.count()} 个指标:')
                    for kpi in metrics:
                        update_needed = force
                        if not force and kpi.last_updated:
                            time_diff = timezone.now() - kpi.last_updated
                            update_needed = time_diff.total_seconds() >= kpi.update_frequency * 60
                        
                        status = "需要更新" if update_needed else "跳过(未到更新时间)"
                        self.stdout.write(f'  - {kpi.name}: {status}')
                    
                    return
                
                # 实际更新
                result = analytics_engine.update_kpi_metrics()
                
                self.stdout.write(
                    self.style.SUCCESS(
                        f'KPI指标更新完成: 成功 {result["updated_count"]} 个，失败 {result["failed_count"]} 个'
                    )
                )
                
                if result['errors']:
                    self.stdout.write(
                        self.style.WARNING('更新过程中的错误:')
                    )
                    for error in result['errors']:
                        self.stdout.write(f'  - {error}')
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'更新KPI指标失败: {e}')
            )
            logger.error(f'更新KPI指标失败: {e}')
            raise